<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Shengshikejibudaipiao extends AbstractApi
{
    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $account =$bean->getAccount();
        $type = "OTHER";
        if (preg_match("/^1[1-9]\d{9}$/", $account)) {
            $type = 'PHONE';
        } elseif (preg_match("/^\d{5,12}$/isu", $account)) {
            $type = "QQ";
        }
        $array = [
            'trade_order_no' => $bean->getOrderNo(), //订单号
            'app_id' => $bean->getSupplierNum(),
            'timestamp' => time(),
            'code' => $bean->getGoodsId(), //商品编码
            'account' => $account,
            'sign_method' => 'md5',
            'account_type' => $type,
            'notify_url'=>$bean->getNotifyUrl(), //异步回调地址
        ];

        $array['sign'] = $this -> sign($array,$bean -> getSecretKey());
        return $array;
    }

    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key){
        ksort($array);
        return strtoupper(md5(urldecode(http_build_query($array)). $secret_key));
    }
    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('order_status', '');
        $order_sn = $request->input('trade_order_no', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['SUCCESS', 'FAILED']))->setRechargeSuccess($status == 'SUCCESS');
    }

    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response('success');
    }
}
